package com.example.translateappjava.Activity.HomeFragmentActivity.Forum;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.translateappjava.Adapter.PostAdapter;
import com.example.translateappjava.R;
import com.example.translateappjava.Repository.PostRepository;
import com.example.translateappjava.Service.ForumApiService.ApiClient;
import com.example.translateappjava.Service.ForumApiService.ApiService;
import com.example.translateappjava.Utils.ApiResponse;
import com.example.translateappjava.Utils.GetPostsRequest;
import com.example.translateappjava.Utils.Post; // 确保导入的是更新后的 Post 类

import java.util.ArrayList;
import java.util.List;
// import java.util.UUID; // 不再为 serverId 生成 UUID

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ForumFragment extends Fragment {

    private static final String TAG = "ForumFragment";
    private List<Post> allPostsMasterList = new ArrayList<>();
    private List<Post> displayedPostsList = new ArrayList<>();
    private ApiService apiService;
    private PostRepository postRepository;
    private RecyclerView recyclerPosts;
    private PostAdapter postAdapter;
    private TextView categoryAll, categoryRecipes, categoryDiary, categoryScience, categoryShare;
    private View currentSelectedCategoryView;
    private String currentSelectedCategoryName = "全部";

    private ForumListener forumListener;

    public static ForumFragment newInstance() {
        return new ForumFragment();
    }

    public interface ForumListener {
        void onPostClick(Post post);
        void onSearchClick(ArrayList<Post> allPosts);
        void onAddPostClick();
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof ForumListener) {
            forumListener = (ForumListener) context;
        } else {
            throw new RuntimeException(context.toString() + " must implement ForumListener");
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getActivity() != null) {
            apiService = ApiClient.getClient().create(ApiService.class);
            postRepository = new PostRepository(getActivity().getApplication());
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.forum_layout, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews(view);

        postAdapter = new PostAdapter(displayedPostsList, clickedPost -> {
            if (forumListener != null) {
                forumListener.onPostClick(clickedPost);
            }
        });
        recyclerPosts.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerPosts.setAdapter(postAdapter);

        setupCategories();
        loadInitialData();
    }

    private void initViews(View view) {
        recyclerPosts = view.findViewById(R.id.recycler_posts);
        categoryAll = view.findViewById(R.id.category_all);
        categoryRecipes = view.findViewById(R.id.category_recipes);
        categoryDiary = view.findViewById(R.id.category_diary);
        categoryScience = view.findViewById(R.id.category_science);
        categoryShare = view.findViewById(R.id.category_share);

        if (categoryAll != null) categoryAll.setText("全部");
        if (categoryRecipes != null) categoryRecipes.setText("营养食谱");
        if (categoryDiary != null) categoryDiary.setText("饮食日记");
        if (categoryScience != null) categoryScience.setText("健康科普");
        if (categoryShare != null) categoryShare.setText("经验分享");

        view.findViewById(R.id.btn_search).setOnClickListener(v -> {
            if (forumListener != null) {
                ArrayList<Post> postsToPass = new ArrayList<>(allPostsMasterList);
                forumListener.onSearchClick(postsToPass);
            }
        });
        view.findViewById(R.id.btn_add).setOnClickListener(v -> {
            if (forumListener != null) {
                forumListener.onAddPostClick();
            }
        });
    }

    private void setupCategories() {
        View.OnClickListener categoryClickListener = v -> {
            if (v instanceof TextView) {
                TextView clickedCategoryTextView = (TextView) v;
                String categoryName = clickedCategoryTextView.getText().toString();
                selectCategory(clickedCategoryTextView, categoryName);
            }
        };
        if (categoryAll != null) categoryAll.setOnClickListener(categoryClickListener);
        if (categoryRecipes != null) categoryRecipes.setOnClickListener(categoryClickListener);
        if (categoryDiary != null) categoryDiary.setOnClickListener(categoryClickListener);
        if (categoryScience != null) categoryScience.setOnClickListener(categoryClickListener);
        if (categoryShare != null) categoryShare.setOnClickListener(categoryClickListener);

        if (categoryAll != null) {
            currentSelectedCategoryView = categoryAll;
        }
    }

    private void selectCategory(View categoryView, String categoryDisplayName) {
        if (currentSelectedCategoryView != null) {
            currentSelectedCategoryView.setBackgroundResource(R.drawable.category_normal_bg);
        }
        if (categoryView != null) {
            categoryView.setBackgroundResource(R.drawable.category_selected_bg);
            currentSelectedCategoryView = categoryView;
        } else if (categoryAll != null && "全部".equals(categoryDisplayName)) {
            categoryAll.setBackgroundResource(R.drawable.category_selected_bg);
            currentSelectedCategoryView = categoryAll;
        }

        currentSelectedCategoryName = categoryDisplayName;
        Log.d(TAG, "Category selected: " + categoryDisplayName);
        filterAndDisplayPosts(categoryDisplayName);
    }

    private void filterAndDisplayPosts(String categoryNameToFilter) {
        Log.d(TAG, "Filtering posts for category: " + categoryNameToFilter + ". Master list size: " + allPostsMasterList.size());
        displayedPostsList.clear();
        if (categoryNameToFilter == null || categoryNameToFilter.equalsIgnoreCase("全部")) {
            displayedPostsList.addAll(allPostsMasterList);
        } else {
            for (Post post : allPostsMasterList) {
                if (post.getCategory() != null && post.getCategory().equalsIgnoreCase(categoryNameToFilter)) {
                    displayedPostsList.add(post);
                }
            }
        }
        Log.d(TAG, "Displayed posts list size after filter: " + displayedPostsList.size());

        if (postAdapter != null) {
            postAdapter.notifyDataSetChanged();
            Log.d(TAG, "Adapter notified of data set change.");
        } else {
            Log.w(TAG, "PostAdapter is null when trying to notifyDataSetChanged.");
        }

        if (displayedPostsList.isEmpty() && getContext() != null) {
            boolean isTrulyEmptyForAll = (categoryNameToFilter == null || categoryNameToFilter.equalsIgnoreCase("全部")) && allPostsMasterList.isEmpty();
            if (!isTrulyEmptyForAll && !(categoryNameToFilter == null || categoryNameToFilter.equalsIgnoreCase("全部"))) {
                Toast.makeText(getContext(), "此分类下暂无帖子", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void loadInitialData() {
        if (postRepository == null || !isAdded()) {
            if (isAdded()) {
                Log.w(TAG, "PostRepository is null, attempting to fetch from server directly for initial load.");
                fetchAllPostsFromServer(true);
            }
            return;
        }
        Log.d(TAG, "Initial load: Loading posts from DB...");
        postRepository.getAllPosts(new PostRepository.RepositoryCallback<List<Post>>() {
            @Override
            public void onSuccess(List<Post> postsFromDb) {
                if (!isAdded()) return;
                Log.d(TAG, "Initial load: Loaded " + (postsFromDb != null ? postsFromDb.size() : 0) + " posts from DB.");
                allPostsMasterList.clear();
                if (postsFromDb != null) {
                    allPostsMasterList.addAll(postsFromDb);
                }
                selectCategory(categoryAll, "全部");

                fetchAllPostsFromServer(false);
            }

            @Override
            public void onError(Exception e) {
                if (!isAdded()) return;
                Log.e(TAG, "Initial load: Error loading posts from DB", e);
                if (getContext() != null) {
                    Toast.makeText(getContext(), "加载本地数据失败", Toast.LENGTH_SHORT).show();
                }
                fetchAllPostsFromServer(false);
            }
        });
    }

    private void fetchAllPostsFromServer(boolean switchToAllAndScroll) {
        if (apiService == null || postRepository == null || !isAdded()) {
            Log.w(TAG, "Cannot fetch from server: Components not ready or Fragment not added.");
            return;
        }
        Log.d(TAG, "Fetching ALL posts from server... switchToAllAndScroll: " + switchToAllAndScroll);

        GetPostsRequest request = new GetPostsRequest(null); // Assuming null means fetch all
        apiService.getPosts(request).enqueue(new Callback<ApiResponse<List<Post>>>() {
            @Override
            public void onResponse(@NonNull Call<ApiResponse<List<Post>>> call, @NonNull Response<ApiResponse<List<Post>>> response) {
                if (!isAdded()) return;

                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<List<Post>> apiResponse = response.body();
                    if (apiResponse.isSuccessful() && apiResponse.getData() != null) {
                        final List<Post> fetchedPosts = apiResponse.getData();
                        Log.d(TAG, "Successfully fetched ALL posts. Count: " + fetchedPosts.size());

                        // *** 修改点 1: 处理服务器返回的帖子的 serverId ***
                        // 服务器应该为每个帖子返回一个 Long 型的 serverId。
                        // 我们不再为 serverId 生成客户端UUID。
                        // 如果服务器返回的 serverId 为 null，这表示数据有问题，需要记录。
                        for (Post post : fetchedPosts) {
                            if (post.getServerId() == null) {
                                Log.w(TAG, "Fetched post (Title: '" + post.getTitle() + "') from server has NULL serverId!");
                                // 根据业务逻辑决定如何处理：
                                // 1. 忽略这个帖子 (不加入列表)
                                // 2. 尝试给它一个临时的本地标识（但不应该是 serverId）
                                // 3. 允许它进入列表，但某些依赖 serverId 的功能可能失效
                                // 这里我们暂时允许它进入，但你可能需要更严格的处理
                            }
                            // 客户端不应再修改从服务器获取的 serverId
                        }

                        postRepository.insertAllPosts(fetchedPosts, new PostRepository.OperationStatusCallback() {
                            @Override
                            public void onSuccess() {
                                if (!isAdded()) return;
                                Log.d(TAG, "Posts from server saved to DB successfully.");
                                loadPostsFromDbAndRefreshUI(switchToAllAndScroll);
                            }

                            @Override
                            public void onError(Exception e) {
                                if (!isAdded()) return;
                                Log.e(TAG, "Error saving posts from server to DB", e);
                                if(getContext() != null) Toast.makeText(getContext(), "无法将服务器数据保存到本地", Toast.LENGTH_SHORT).show();
                                // Fallback
                                allPostsMasterList.clear();
                                allPostsMasterList.addAll(fetchedPosts);
                                if (switchToAllAndScroll) {
                                    selectCategory(categoryAll, "全部");
                                    if (recyclerPosts != null) recyclerPosts.smoothScrollToPosition(0);
                                } else {
                                    filterAndDisplayPosts(currentSelectedCategoryName);
                                }
                            }
                        });
                    } else {
                        String errorMessage = apiResponse != null ? apiResponse.getMessage() : "服务器数据错误";
                        Log.e(TAG, "API reported an error: " + errorMessage);
                        if(getContext() != null) Toast.makeText(getContext(), "获取帖子失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.e(TAG, "Failed to fetch ALL posts. Code: " + response.code() + ", Message: " + response.message());
                    if(getContext() != null) Toast.makeText(getContext(), "获取帖子失败: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(@NonNull Call<ApiResponse<List<Post>>> call, @NonNull Throwable t) {
                if (!isAdded()) return;
                Log.e(TAG, "Error fetching ALL posts from server: " + t.getMessage(), t);
                if(getContext() != null) Toast.makeText(getContext(), "网络请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void loadPostsFromDbAndRefreshUI(boolean switchToAllAndScroll) {
        if (postRepository == null || !isAdded()) return;
        Log.d(TAG, "Loading posts from DB to refresh UI. switchToAllAndScroll: " + switchToAllAndScroll);
        postRepository.getAllPosts(new PostRepository.RepositoryCallback<List<Post>>() {
            @Override
            public void onSuccess(List<Post> postsFromDb) {
                if (!isAdded()) return;
                Log.d(TAG, "Loaded " + (postsFromDb != null ? postsFromDb.size() : 0) + " posts from DB for UI refresh.");
                allPostsMasterList.clear();
                if (postsFromDb != null) {
                    allPostsMasterList.addAll(postsFromDb);
                }

                if (switchToAllAndScroll) {
                    View targetCategoryView = categoryAll != null ? categoryAll : (getView() != null ? getView().findViewById(R.id.category_all) : null);
                    selectCategory(targetCategoryView, "全部");
                    if (recyclerPosts != null) {
                        recyclerPosts.smoothScrollToPosition(0);
                        Log.d(TAG, "Scrolled to position 0 after server sync.");
                    }
                } else {
                    filterAndDisplayPosts(currentSelectedCategoryName);
                }
            }

            @Override
            public void onError(Exception e) {
                if (!isAdded()) return;
                Log.e(TAG, "Error loading posts from DB for UI refresh", e);
            }
        });
    }

    public void refreshData() {
        if (isAdded()) {
            fetchAllPostsFromServer(false);
        }
    }

    public void addPostToList(Post newPost) { // newPost 是从 CreatePostActivity 返回的，应该有 serverId
        if (newPost == null || postRepository == null || !isAdded()) return;

        postRepository.insertPost(newPost, new PostRepository.OperationStatusCallback() {
            @Override
            public void onSuccess() {
                if (!isAdded()) return;
                // *** 修改点 2: 更新日志中的ID获取方式 ***
                Log.d(TAG, "New post (ServerID: " + newPost.getServerId() + ", LocalID: " + newPost.getLocalId() + ") saved to local DB successfully.");
                fetchAllPostsFromServer(true);
            }

            @Override
            public void onError(Exception e) {
                if (!isAdded()) return;
                Log.e(TAG, "Error saving new post to local DB", e);
                if (getContext() != null) {
                    Toast.makeText(getContext(), "无法将新帖子保存到本地", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onDetach() {
        super.onDetach();
        forumListener = null;
    }
}